<?php

namespace IDock\Insurance\QHIC\Response;

use IDock\Http\Response;
use IDock\IDock\IDockEnums;
use IDock\Insurance\QHIC\QHICEnums;
use IDock\Printer\NonCar\NonCarInquiryPrinter;
use IDock\Printer\NonCar\NonCarInquirySinglePrinter;
use IDock\Printer\Premium\PremiumBIPrinter;
use IDock\Printer\Premium\PremiumCoveragePrinter;
use IDock\Printer\Premium\PremiumInquiryPrinter;
use IDock\Printer\SpecialClausesPrinter;

class PremiumInquiryResponse extends AllQHICResponse
{
    public function resolve(): Response
    {
        if ($this->printer and is_string($this->printer)) {
            $this->printer = new $this->printer;
        }
        $body = $this->getBody();
        if (!json_decode($body)) {
            $this->setError('返回数据异常');
            return $this;
        }
        $data = json_decode($body, true);

        $resultCode = $data['Head']['ErrorCode'] ?? '';
        $resultMess = $data['Head']['ErrorMessage'] ?? '';
        if ($resultCode != '0000' && strpos($resultMess, '重复投保') === false) {
            $this->printer->success = false;
            $this->setError($resultMess);
            return $this;
        }
        $this->setBody($data);

        return $this;
    }

    /**
     * @var PremiumInquiryPrinter $printer
     * @var  $printer
     */
    public $printer = PremiumInquiryPrinter::class;

    protected $records = [];

    protected $result = [];

    public $planCode = '';

    public $productCode = '';

    public $insuredNum = 1;

    private $loyaltyType = [
        '1' => '续',
        '2' => '转',
        '3' => '新',
    ];

    public function printerInit(): Response
    {

        if (!$this->printer->success) {
            return $this;
        }
        $body = $this->getBody() ?? [];
        if (isset($body['VhlList'])) {
            $this->setError("请重新选择车型再算价");
            $this->printer->success = false;
            return $this;
        }
        //重复投保
        $resultMess = $body['Head']['ErrorMessage'] ?? '';
        if (strpos($resultMess, '重复投保') !== false) {
            $this->repeat($resultMess);
            if ($this->printer->repeatInsuredFlg) {
                $this->printer->success = false;
                return $this;
            }
            $this->setError($resultMess);
            return $this;
        }
        $mainData = $body['Base'] ?? [];

        //商业险重复投保
        $biMsg = $mainData['CRepeatMsg'] ?? '';
        if (isset($biMsg)) {
            $this->repeat($biMsg);
            if ($this->printer->repeatInsuredFlg) {
                $this->printer->success = false;
                return $this;
            }
        }
        $Vhl = $body['Vhl'] ?? [];
        //车船税
        if ($carShipTax = $body['VsTax'] ?? '') {
            $this->printer->carTaxPrinter->carShipTax = $carShipTax['NAggTax'] ?? '';
            $this->printer->carTaxPrinter->overdue = $carShipTax['NOverdueAmt'] ?? '';
            $this->printer->carTaxPrinter->thisYearTax = $carShipTax['NTaxableAmt'] ?? '';
        }
        //交强险
        $this->printer->ciPremiumPrinter->ciPremium = $mainData['NPrm'] ?? '';
        $this->printer->ciPremiumPrinter->ciStartData = $this->timeFormat($mainData['TInsrncBgnTm'] ?? '');
        $this->printer->ciPremiumPrinter->ciEndData = $this->timeFormat($mainData['TInsrncEndTm'] ?? '');
        $this->printer->ciInquiryNo = $mainData['CAppNo'] ?? '';
        $this->printer->argc['CAppNo'] = $this->printer->ciInquiryNo;
        $this->printer->premiumFactorPrinter->TCIFactorAppend('交强预期赔付率', 'NBillCTPELR', $body['PrmCoef']['NBillCTPELR'] ?? '');
        $this->printer->premiumFactorPrinter->TCIFactorAppend('交强险忠诚度','CIRenewalType',$this->loyaltyType[$Vhl['CJQBusinessType'] ?? ''] ?? '');
        $riskArr = $body['CvrgList'] ?? [];
        foreach ($riskArr as $row) {
            if ($row['CCvrgNo'] == '030000') {
                //交强险
                continue;
            }
            $coverage = new PremiumCoveragePrinter();
            $coverage->coverageCode = array_search($row['CCvrgNo'], QHICEnums::$coverageCode);
            $coverage->coverageName = IDockEnums::$coverageCode[$coverage->coverageCode];
            $coverage->amount = $row['NAmt'] ?? 0;
            $coverage->unitAmount = $row['NPerAmt'] ?? 0;
            $coverage->quantity = $row['NLiabDaysLmt'] ?? 0;
            $coverage->premium = $row['NPrm'] ?? 0;
            $coverage->serviceTimes = $row['NServiceTimes'] ?? '0';
            $this->printer->coverageListAppend($coverage);
        }
        //商业险
        $this->printer->biPremiumPrinter = new PremiumBIPrinter();
        $this->printer->biPremiumPrinter->biPremium = $mainData['SY_NPrm'] ?? '';
        $this->printer->biPremiumPrinter->biStartData = $this->timeFormat($mainData['SY_TInsrncBgnTm'] ?? '');
        $this->printer->biPremiumPrinter->biEndData = $this->timeFormat($mainData['SY_TInsrncEndTm'] ?? '');
        $this->printer->biInquiryNo = $mainData['SY_CAppNo'] ?? '';
        $this->printer->argc['SY_CAppNo'] = $this->printer->biInquiryNo;
        $this->printer->ncdFactor = $mainData['NResvNum6'] ?? '';
        //商业险系数
        $this->printer->premiumFactorPrinter->VCIFactorAppend('商业预期赔付率', 'NBillCOMELR', $body['PrmCoef']['NBillCOMELR'] ?? '');
        $this->printer->premiumFactorPrinter->VCIFactorAppend('商业险忠诚度', 'BIRenewalType', $this->loyaltyType[$Vhl['CSYBusinessType'] ?? ''] ?? '');

        $this->printer->premiumFactorPrinter->ComFactorAppend('短期系数', 'NRatioCoef', $mainData['NRatioCoef'] ?? '');
        $this->printer->premiumFactorPrinter->ComFactorAppend('折扣率', 'NDiscRate', $mainData['NDiscRate'] ?? '');
        $this->printer->premiumFactorPrinter->ComFactorAppend('浮动率（商业）', 'SY_NIrrRatio', $main['SY_NIrrRatio'] ?? '');
        $this->printer->premiumFactorPrinter->ComFactorAppend('浮动率（交强）', 'JQ_NTotDisc', $main['JQ_NTotDisc'] ?? '');
        $this->printer->premiumFactorPrinter->ComFactorAppend('上年出险次数', 'NLastYearRiskTimes', $main['NLastYearRiskTimes'] ?? '');
        $this->printer->premiumFactorPrinter->ComFactorAppend('期望折扣', 'NLastYearRiskTimes', $body['PrmCoef']['NExpDisc'] ?? '');
        $this->printer->premiumFactorPrinter->ComFactorAppend('交商合计预期赔付率', 'NBillELR', $body['PrmCoef']['NBillELR'] ?? '');
        $this->printer->premiumFactorPrinter->ComFactorAppend('自主定价系数', 'NPricingAdjustValue', $body['PrmCoef']['NPricingAdjustValue'] ?? '');

        //特约
        $specialClause = [
            [
                'clauseCode' => '022101000000031030001',
                'clausesName' => '非营业车辆特约',
                'clausesContext' => '非营业车辆如从事营业性运输，发生保险责任范围内的事故，本公司不承担任何赔偿责任。'
            ],
            [
                'clauseCode' => '024403000000022030001',
                'clausesName' => '验车不合格特约',
                'clausesContext' => '本车投保时有损伤，损伤部位为*，损伤情况以投保时验车照片为准。在修复前，保险人不承担此损失赔偿责任，修复后请及时到我公司进行验车、批改保单约定。'
            ],
            [
                'clauseCode' => '024403000000017030001',
                'clausesName' => '车辆改装免责特约',
                'clausesContext' => '被保险机动车改装、加装，被保险人、受让人未及时通知保险人，且因改装、加装等导致被保险机动车危险程度显著增加，导致人身伤亡、财产损失和费用时，保险人不负责赔偿。'
            ],
            [
                'clauseCode' => '027401000000012030001',
                'clausesName' => '重复投保特约',
                'clausesContext' => '保险事故发生时，保险车辆重复保险的，保险人按照本保险合同保险金额与各保险合同保险保额的总额比例承担赔偿责任。'
            ],
        ];
        foreach ($specialClause as $value) {
            $specialClauses = new SpecialClausesPrinter();
            $specialClauses->clauseCode = $value['clauseCode'] ?? '';
            $specialClauses->clauseName = $value['clausesName'] ?? '';
            $specialClauses->clauseContent = $value['clausesContext'] ?? '';
            $specialClauses->riskType = 'TCI';
            $this->printer->specialClausesAppend($specialClauses);
        }


        //非车
        $this->printer->nonCarInquiryPrinter = new NonCarInquiryPrinter();

        if ($body['NovehicleList'] ?? []) {

            foreach ($body['NovehicleList'] ?? [] as $noVehicle) {
                $single = new NonCarInquirySinglePrinter();
                $single->premium = $noVehicle['NPrm'] ?? '';
                $single->inquiryNo = $noVehicle['CNovehicleAppNo'] ?? '';
                $single->amount = $noVehicle['NAmt'] ?? '';
                $single->statusCode = 'success';
                $single->argc = [];

                foreach ($noVehicle['NovehicleCvrgList'] ?? [] as $item) {
                    $single->argc[$item['CCvrgNo']] = $item['CCvrgNo'] . '--' . $item['NPrm'] ?? '';
                }
                ksort($single->argc);
                $single->argc = implode(',', $single->argc);

                $this->printer->nonCarInquiryPrinter->totalPremium += $single->premium;
                $this->printer->nonCarInquiryPrinter->noCarInquirySingleAppend($single);
            }
        }

        return $this;
    }

    /**
     * 重复投保
     * @param $errMeg
     */
    private function repeat($errMeg)
    {
        if (preg_match('/交强险[\s\S]*终保日期 ([\d\s:-]+)/', $errMeg, $matches)) {
            if ($matches[1] ?? '') {
                $ciStartData = date('Y-m-d H:i:s', strtotime($matches[1]));
                $this->printer->repeatInsurePrinter['ciStartData'] = $ciStartData;
                $this->printer->repeatInsuredFlg = true;
                $this->printer->repeatMessage = $errMeg;
            }
        }

        if (preg_match('/商业险[\s\S]*终保日期：([\d\s:-]+)/', $errMeg, $matches)) {
            if ($matches[1] ?? '') {
                $biStartData = date('Y-m-d H:i:s', strtotime($matches[1]));
                $this->printer->repeatInsurePrinter['biStartData'] = $biStartData;
                $this->printer->repeatInsuredFlg = true;
                $this->printer->repeatMessage = $errMeg;
            }
        }
    }

    public function newEnergy()
    {
        /**@var PremiumCoveragePrinter $value ** */
        foreach ($this->printer->coverageList as $value) {
            $value->coverageCode = 'C1' . substr($value->coverageCode, 2);
        }

    }

    private function timeFormat($date)
    {
        if (empty($date)) return '';
        return date('Y-m-d H:i:s', strtotime($date));
    }
}
